<template>
    <div class="purchaser-dashboard">
  <el-card class="dashboard-header">
        <h2>采购员仪表盘</h2>
        <p>这里是采购员的仪表盘，展示一些统计数据和图表。</p>
      </el-card>

  <!-- 本月采购订单 -->
  <el-card class="dashboard-card">
              <template #header>
                <div class="card-header-with-icon">
                  <el-icon><ShoppingCart /></el-icon>
                  <span>本月采购订单</span>
                </div>
              </template>
    <div class="card-content">
      <div class="statistic-section">
              <div class="statistic-value">{{ statistics.monthlyOrders }}</div>
              <div class="statistic-label">较上月 {{ statistics.orderGrowth > 0 ? '+' : '' }}{{ statistics.orderGrowth }}%</div>
      </div>
      <div class="chart-section">
        <div class="chart-header">
          <span>采购数量趋势</span>
          <el-radio-group v-model="quantityTimeRange" size="small">
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
        </div>
        <div ref="quantityChartRef" style="height: 300px"></div>
      </div>
    </div>
            </el-card>

  <!-- 本月采购金额 -->
  <el-card class="dashboard-card">
              <template #header>
                <div class="card-header-with-icon">
                  <el-icon><Money /></el-icon>
                  <span>本月采购金额</span>
                </div>
              </template>
    <div class="card-content">
      <div class="statistic-section">
              <div class="statistic-value">¥{{ statistics.monthlyAmount.toLocaleString() }}</div>
              <div class="statistic-label">较上月 {{ statistics.amountGrowth > 0 ? '+' : '' }}{{ statistics.amountGrowth }}%</div>
                </div>
      <div class="chart-section">
        <div class="chart-header">
          <span>采购金额趋势</span>
          <el-radio-group v-model="amountTimeRange" size="small">
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
                </div>
        <div ref="amountChartRef" style="height: 300px"></div>
      </div>
    </div>
            </el-card>
  
  <!-- 库存预警 -->
  <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
        <div class="card-header-with-icon">
          <el-icon><Warning /></el-icon>
          <span>库存预警</span>
        </div>
        <el-select v-model="selectedWarehouse" placeholder="选择仓库" @change="fetchStockWarnings" style="width: 150px">
                <el-option
                  v-for="warehouse in warehouses"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.id"
                />
              </el-select>
            </div>
          </template>
    <div class="warning-summary">
      <div class="warning-count">
        <el-icon><Warning /></el-icon>
        <span>{{ statistics.stockWarnings }} 个商品需要补货</span>
      </div>
    </div>
          <el-table :data="stockWarnings" style="width: 100%">
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="currentStock" label="当前库存" />
            <el-table-column prop="minStock" label="最低库存" />
            <el-table-column prop="gap" label="库存缺口">
              <template #default="{ row }">
                <span :class="{ 'text-danger': row.gap > 0 }">
                  {{ row.gap > 0 ? `-${row.gap}` : '0' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="getStockStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleQuickPurchase(row)"
                  :disabled="row.gap <= 0"
                >
                  采购
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
  
  <!-- 仓库库存情况 -->
  <el-card class="warehouse-inventory-card">
          <template #header>
            <div class="card-header">
        <div class="title">仓库库存情况</div>
            </div>
          </template>
    <el-table :data="warehouseInventory" v-loading="inventoryLoading">
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-table :data="row.products" border size="small" style="margin-left: 50px; width: calc(100% - 50px)">
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="current_stock" label="当前库存" width="120" />
            <el-table-column prop="min_stock" label="最低库存" width="120" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStockStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="warehouse_name" label="仓库名称" />
      <el-table-column prop="total_products" label="商品种类" />
      <el-table-column prop="normal_count" label="正常库存">
        <template #default="{ row }">
          <el-tag type="success">{{ row.normal_count }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="warning_count" label="低库存">
        <template #default="{ row }">
          <el-tag type="warning">{{ row.warning_count }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="overflow_count" label="超量库存">
        <template #default="{ row }">
          <el-tag type="danger">{{ row.overflow_count }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
        </el-card>
  
        <!-- 快速采购对话框 -->
        <el-dialog
          v-model="purchaseDialogVisible"
          title="快速采购"
          width="500px"
        >
          <el-form
          ref="purchaseFormRef"
            :model="purchaseForm"
            :rules="purchaseRules"
            label-width="100px"
          >
            <el-form-item label="产品名称">
              <span>{{ currentProduct?.name }}</span>
            </el-form-item>
            <el-form-item label="采购数量" prop="quantity">
              <el-input-number 
                v-model="purchaseForm.quantity" 
                :min="1" 
              :step="1"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="预计到货" prop="expectedDate">
              <el-date-picker
                v-model="purchaseForm.expectedDate"
                type="date"
                placeholder="选择日期"
                :disabled-date="disabledDate"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="purchaseForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="purchaseDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handlePurchaseSubmit">确认采购</el-button>
            </span>
          </template>
        </el-dialog>
    </div>
  </template>
  
  <script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
  import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
  import {
  TitleComponent,
    TooltipComponent,
    LegendComponent,
  GridComponent
  } from 'echarts/components'
import { PieChart, LineChart } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
  import {
    ShoppingCart,
    Money,
    Warning,
  } from '@element-plus/icons-vue'
  import axios from 'axios'
  import { getToken } from '@/utils/auth'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 注册必需的组件
echarts.use([
  TitleComponent,
    TooltipComponent,
    LegendComponent,
  GridComponent,
  PieChart,
  LineChart,
  LabelLayout,
  CanvasRenderer
  ])
  
  // 统计数据
  const statistics = ref({
    monthlyOrders: 0,
    orderGrowth: 0,
    monthlyAmount: 0,
    amountGrowth: 0,
    stockWarnings: 0,
  })
  
  // 仓库和库存预警数据
  const warehouses = ref([])
  const selectedWarehouse = ref('')
  const stockWarnings = ref([])

// 仓库库存数据
const warehouseInventory = ref([])
const inventoryLoading = ref(false)

// 图表相关的响应式数据
const amountTimeRange = ref('month')
const quantityTimeRange = ref('month')
const amountChartRef = ref(null)
const quantityChartRef = ref(null)
const amountChart = ref(null)
const quantityChart = ref(null)

// 商品类别缓存
const productCategoryCache = new Map()

// 验证响应是否是HTML
const isHtmlResponse = (data) => {
  if (typeof data === 'string' && data.trim().startsWith('<!DOCTYPE html>')) {
    return true
  }
  return false
}

// 验证token并获取新token
const validateAndRefreshToken = async () => {
  const token = getToken()
  if (!token) {
    throw new Error('No token found')
  }
  
  // 可以在这里添加token刷新的逻辑
  return token
}
  
  // 获取仓库列表
  const fetchWarehouses = async () => {
    try {
      const token = await validateAndRefreshToken()
      if (!token) {
        ElMessage.warning('请先登录')
        return
      }

      console.log('Fetching warehouses...')
      const response = await axios.get('/api/warehouses/', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
    console.log('Warehouses response:', response.data)
    
    // 处理不同的响应格式
    let warehouseList = []
    if (Array.isArray(response.data)) {
      warehouseList = response.data
    } else if (response.data?.results && Array.isArray(response.data.results)) {
      warehouseList = response.data.results
    } else if (response.data?.data && Array.isArray(response.data.data)) {
      warehouseList = response.data.data
    }

    // 过滤出启用状态的仓库
    warehouseList = warehouseList.filter(warehouse => warehouse.status === 'active')

    // 根据仓库类型排序：常温 -> 冷藏 -> 冷冻
    const typeOrder = { normal: 1, cold: 2, frozen: 3 }
    warehouseList.sort((a, b) => typeOrder[a.type] - typeOrder[b.type])

    console.log('Processed warehouse list:', warehouseList)

    // 添加"全部仓库"选项，并确保其他选项包含必要的字段
    warehouses.value = [
      { id: '', name: '全部仓库', type: 'all' },
      ...warehouseList.map(warehouse => ({
        id: warehouse.id,
        name: warehouse.name || '未命名仓库',
        type: warehouse.type || 'normal',
        location: warehouse.location || '未知位置'
      }))
    ]

    // 默认选择"全部仓库"
    selectedWarehouse.value = ''

    console.log('Updated warehouses ref:', warehouses.value)
    console.log('Selected warehouse:', selectedWarehouse.value)

    // 获取库存预警数据
    await fetchStockWarnings()
    } catch (error) {
    console.error('获取仓库列表失败:', error.response || error)
      ElMessage.error('获取仓库列表失败')
      warehouses.value = [{ id: '', name: '全部仓库', type: 'all' }]
      selectedWarehouse.value = ''
    }
  }
  
  // 获取库存预警数据
  const fetchStockWarnings = async () => {
    try {
    const token = await validateAndRefreshToken()
      if (!token) {
        ElMessage.warning('请先登录')
        return
      }

    console.log('Fetching stock warnings...')
    console.log('Selected warehouse:', selectedWarehouse.value)

    // 获取所有产品的库存信息
    const response = await axios.get('/api/inventory/', {
        headers: {
          'Authorization': `Bearer ${token}`
        },
        params: {
        warehouse_id: selectedWarehouse.value || undefined
      }
    })

    console.log('Stock warnings response:', response.data)

    // 处理响应数据
    let inventoryData = []
    if (Array.isArray(response.data)) {
      inventoryData = response.data
    } else if (response.data?.results) {
      inventoryData = response.data.results
    } else if (response.data?.data) {
      inventoryData = response.data.data
    }

    // 过滤出库存预警的商品（当前库存小于等于最低库存）
    const warningItems = inventoryData.filter(item => {
      const currentStock = Number(item.current_stock || 0)
      const minStock = Number(item.min_stock || 0)
      return currentStock <= minStock
    })

    console.log('Warning items:', warningItems)

    // 转换为前端显示格式
    stockWarnings.value = await Promise.all(warningItems.map(async item => {
      // 获取产品详细信息
      let productDetail = {}
      try {
        const productResponse = await axios.get(`/api/products/${item.product}/`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        productDetail = productResponse.data
      } catch (error) {
        console.error('获取产品详情失败:', error)
      }

      return {
        id: item.product,
        name: item.product_name || productDetail.name || '未知产品',
        currentStock: Number(item.current_stock || 0),
        minStock: Number(item.min_stock || 0),
        gap: Math.max(0, (item.min_stock || 0) - (item.current_stock || 0)),
        status: getStockStatusText(item.current_stock, item.min_stock),
        warehouse_id: item.warehouse, // 添加仓库ID
        warehouse_name: item.warehouse_name || '未知仓库',
        cost_price: Number(productDetail.cost_price || 0)
      }
    }))

    console.log('Processed stock warnings:', stockWarnings.value)

    // 更新统计数据中的库存预警数量
    statistics.value = {
      ...statistics.value,
      stockWarnings: stockWarnings.value.length
    }
    } catch (error) {
      console.error('获取库存预警数据失败:', error)
      ElMessage.error('获取库存预警数据失败')
      stockWarnings.value = []
    }
  }
  
// 获取仓库库存数据
const fetchWarehouseInventory = async () => {
  try {
    inventoryLoading.value = true
    const token = await validateAndRefreshToken()
      if (!token) {
        ElMessage.warning('请先登录')
        return
      }

    console.log('Fetching warehouse inventory...')
    const response = await axios.get('/api/inventory/', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

    console.log('Warehouse inventory response:', response.data)

    // 处理响应数据
    let inventoryData = []
    if (Array.isArray(response.data)) {
      inventoryData = response.data
    } else if (response.data?.results) {
      inventoryData = response.data.results
    } else if (response.data?.data) {
      inventoryData = response.data.data
    }

    console.log('Processed inventory data:', inventoryData)

    // 按仓库分组统计
    const warehouseStats = {}
    inventoryData.forEach(item => {
      const warehouseName = item.warehouse_name || '未知仓库'
      if (!warehouseStats[warehouseName]) {
        warehouseStats[warehouseName] = {
          warehouse_name: warehouseName,
          total_products: 0,
          normal_count: 0,
          warning_count: 0,
          overflow_count: 0,
          products: []
        }
      }

      // 添加商品信息
      warehouseStats[warehouseName].products.push({
        name: item.product_name || '未知商品',
        current_stock: Number(item.current_stock || 0),
        min_stock: Number(item.min_stock || 0),
        max_stock: Number(item.max_stock || 0),
        status: getInventoryStatus(item)
      })

      warehouseStats[warehouseName].total_products++

      // 根据库存状态计数
      const status = getInventoryStatus(item)
      if (status === '低库存') {
        warehouseStats[warehouseName].warning_count++
      } else if (status === '超量') {
        warehouseStats[warehouseName].overflow_count++
      } else {
        warehouseStats[warehouseName].normal_count++
      }
    })

    console.log('Warehouse stats:', warehouseStats)

    // 转换为数组并对商品列表排序
    warehouseInventory.value = Object.values(warehouseStats).map(warehouse => ({
      ...warehouse,
      products: warehouse.products.sort((a, b) => a.name.localeCompare(b.name))
    }))

    console.log('Final warehouse inventory:', warehouseInventory.value)
  } catch (error) {
    console.error('获取仓库库存数据失败:', error.response || error)
    ElMessage.error('获取仓库库存数据失败')
    warehouseInventory.value = []
  } finally {
    inventoryLoading.value = false
  }
}

// 获取库存状态
const getInventoryStatus = (item) => {
  const currentStock = Number(item.current_stock || 0)
  const minStock = Number(item.min_stock || 0)
  const maxStock = Number(item.max_stock || 0)

  if (currentStock <= minStock) {
    return '低库存'
  } else if (maxStock && currentStock > maxStock) {
    return '超量'
  } else {
    return '正常'
  }
}

// 获取库存状态样式
const getStockStatusType = (status) => {
  const typeMap = {
    '正常': 'success',
    '低库存': 'warning',
    '超量': 'danger'
  }
  return typeMap[status] || 'info'
  }
  
  // 获取库存状态文本
  const getStockStatusText = (currentStock, minStock) => {
    currentStock = Number(currentStock || 0)
    minStock = Number(minStock || 0)
    
    if (currentStock <= 0) {
      return '无库存'
    } else if (currentStock <= minStock) {
      return '低库存'
    } else {
    return '正常'
  }
  }
  
  // 快速采购相关
  const purchaseDialogVisible = ref(false)
  const currentProduct = ref(null)
  const purchaseForm = ref({
    quantity: 0,
    expectedDate: '',
    remark: ''
  })
  
  const purchaseRules = {
    quantity: [
      { required: true, message: '请输入采购数量', trigger: 'blur' },
      { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
    ],
    expectedDate: [
      { required: true, message: '请选择预计到货日期', trigger: 'change' }
    ]
  }
  
  const handleQuickPurchase = (row) => {
    currentProduct.value = row
    purchaseForm.value = {
      quantity: row.gap,
      expectedDate: '',
      remark: `补充库存：${row.name}`
    }
    purchaseDialogVisible.value = true
  }
  
  const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7
  }
  
  const handlePurchaseSubmit = async () => {
    try {
      const token = await validateAndRefreshToken()
      if (!token) {
        ElMessage.warning('请先登录')
        return
      }

      // 验证表单
      if (!purchaseForm.value.quantity || !purchaseForm.value.expectedDate) {
        ElMessage.warning('请填写完整的采购信息')
        return
      }

      // 验证必要的数据是否存在
      if (!currentProduct.value) {
        ElMessage.error('商品信息不完整')
        return
      }

      if (!currentProduct.value.id) {
        ElMessage.error('商品ID不存在')
        return
      }

      if (!currentProduct.value.cost_price) {
        ElMessage.error('商品采购价格不存在')
        return
      }

      // 获取仓库ID
      const warehouseId = selectedWarehouse.value || currentProduct.value.warehouse_id
      if (!warehouseId) {
        ElMessage.error('请选择仓库')
        return
      }

      console.log('Current product:', currentProduct.value)
      console.log('Selected warehouse:', warehouseId)
      console.log('Purchase form:', purchaseForm.value)

      const orderData = {
        supplier: '优质生鲜供应有限公司', // 默认供应商名称
        expected_delivery_date: purchaseForm.value.expectedDate,
        remark: purchaseForm.value.remark || '',
        items: [{
          product_id: currentProduct.value.id.toString(),
          quantity: purchaseForm.value.quantity.toString(),
          unit_price: currentProduct.value.cost_price.toString(),
          warehouse_id: warehouseId.toString()
        }]
      }

      console.log('Creating purchase order:', orderData)

      const response = await axios.post('/api/purchase-orders/', orderData, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      console.log('Purchase order response:', response.data)

      if (response.data.code === 200) {
      ElMessage.success('采购订单创建成功')
      purchaseDialogVisible.value = false
      
      // 刷新数据
      await Promise.all([
          fetchStockWarnings(),
          fetchWarehouseInventory()
      ])
      } else {
        ElMessage.error(response.data.message || '创建采购订单失败')
      }
    } catch (error) {
      console.error('创建采购订单失败:', error)
      if (error.response?.data) {
        const errorMsg = typeof error.response.data === 'string' 
          ? error.response.data
          : error.response.data.message || Object.values(error.response.data).flat().join(', ')
        ElMessage.error(errorMsg || '创建采购订单失败')
      } else {
        ElMessage.error(error.message || '创建采购订单失败')
      }
    }
  }
  
// 初始化图表
const initCharts = () => {
  nextTick(() => {
    try {
      if (amountChartRef.value && !amountChart.value) {
        amountChart.value = echarts.init(amountChartRef.value)
        console.log('金额趋势图表初始化成功')
      }
    } catch (error) {
      console.error('金额趋势图表初始化失败:', error)
    }

    try {
      if (quantityChartRef.value && !quantityChart.value) {
        quantityChart.value = echarts.init(quantityChartRef.value)
        console.log('数量趋势图表初始化成功')
      }
    } catch (error) {
      console.error('数量趋势图表初始化失败:', error)
    }
  })
}

// 获取采购趋势数据
const fetchPurchaseTrends = async () => {
  try {
    const token = await validateAndRefreshToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 获取时间范围
    const now = new Date()
    const amountRange = amountTimeRange.value
    const quantityRange = quantityTimeRange.value

    // 获取金额趋势的时间范围
    let amountStartDate, amountEndDate
    if (amountRange === 'week') {
      // 获取本周的开始（周一）和结束（周日）
      const day = now.getDay() || 7 // 将周日的0转换为7
      amountStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day + 1)
      amountEndDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (7 - day))
    } else if (amountRange === 'month') {
      // 获取本月的第一天和最后一天
      amountStartDate = new Date(now.getFullYear(), now.getMonth(), 1)
      // 通过设置下个月的第0天来获取本月的最后一天
      amountEndDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
    } else if (amountRange === 'year') {
      // 获取本年的第一天和最后一天
      amountStartDate = new Date(now.getFullYear(), 0, 1)
      amountEndDate = new Date(now.getFullYear(), 11, 31)
    }

    // 获取数量趋势的时间范围
    let quantityStartDate, quantityEndDate
    if (quantityRange === 'week') {
      // 获取本周的开始（周一）和结束（周日）
      const day = now.getDay() || 7 // 将周日的0转换为7
      quantityStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day + 1)
      quantityEndDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (7 - day))
    } else if (quantityRange === 'month') {
      // 获取本月的第一天和最后一天
      quantityStartDate = new Date(now.getFullYear(), now.getMonth(), 1)
      // 通过设置下个月的第0天来获取本月的最后一天
      quantityEndDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
    } else if (quantityRange === 'year') {
      // 获取本年的第一天和最后一天
      quantityStartDate = new Date(now.getFullYear(), 0, 1)
      quantityEndDate = new Date(now.getFullYear(), 11, 31)
    }

    console.log('Amount date range:', {
      start: amountStartDate.toISOString().split('T')[0],
      end: amountEndDate.toISOString().split('T')[0]
    })
    console.log('Quantity date range:', {
      start: quantityStartDate.toISOString().split('T')[0],
      end: quantityEndDate.toISOString().split('T')[0]
    })

    // 获取金额趋势订单数据
    const amountResponse = await axios.get('/api/purchase-orders/', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      },
      params: {
        status: ['confirmed', 'received'].join(','),
        start_date: amountStartDate.toISOString().split('T')[0],
        end_date: amountEndDate.toISOString().split('T')[0]
      }
    })

    // 处理金额趋势数据
    const amountOrders = amountResponse.data?.results || 
                        amountResponse.data?.data?.items || 
                        (Array.isArray(amountResponse.data) ? amountResponse.data : [])

    // 按日期分组金额数据
    const dateAmountMap = new Map()
    amountOrders.forEach(order => {
      const orderDate = order.created_at.split('T')[0]
      const amount = Number(order.total_amount) || 0
      dateAmountMap.set(orderDate, (dateAmountMap.get(orderDate) || 0) + amount)
    })

    // 生成金额趋势日期序列
    const amountDates = []
    const amounts = []
    let currentDate = new Date(amountStartDate)

    while (currentDate <= amountEndDate) {
      const dateStr = currentDate.toISOString().split('T')[0]
      amountDates.push(dateStr)
      amounts.push(dateAmountMap.get(dateStr) || 0)
      currentDate.setDate(currentDate.getDate() + 1)
    }

    // 更新金额趋势图
    updateAmountChart({ dates: amountDates, amounts })

    // 获取数量趋势订单数据
    const quantityResponse = await axios.get('/api/purchase-orders/', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      },
      params: {
        status: ['confirmed', 'received'].join(','),
        start_date: quantityStartDate.toISOString().split('T')[0],
        end_date: quantityEndDate.toISOString().split('T')[0]
      }
    })

    // 处理数量趋势数据
    const quantityOrders = quantityResponse.data?.results || 
                          quantityResponse.data?.data?.items || 
                          (Array.isArray(quantityResponse.data) ? quantityResponse.data : [])

    // 收集所有需要获取详情的商品ID
    const productIds = new Set()
    quantityOrders.forEach(order => {
      if (order.items && Array.isArray(order.items)) {
        order.items.forEach(item => {
          if (item.product_id && !productCategoryCache.has(item.product_id)) {
            productIds.add(item.product_id)
          }
        })
      }
    })

    // 批量获取商品详情
    if (productIds.size > 0) {
      const productRequests = Array.from(productIds).map(productId =>
        axios.get(`/api/products/${productId}/`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'application/json'
          }
        }).then(response => {
          const product = response.data
          productCategoryCache.set(product.id, {
            category: product.category_detail?.name || 
                     product.category?.name || 
                     (typeof product.category === 'string' ? product.category : '未分类'),
            name: product.name
          })
        }).catch(error => {
          console.error(`获取商品 ${productId} 详情失败:`, error)
          productCategoryCache.set(productId, {
            category: '未分类',
            name: '未知商品'
          })
        })
      )

      await Promise.all(productRequests)
    }

    // 初始化类别数量统计
    const categoryQuantities = {
      '新鲜水果': 0,
      '绿色蔬菜': 0,
      '优质肉类': 0,
      '新鲜海鲜': 0
    }

    // 统计每个类别的采购数量
    quantityOrders.forEach(order => {
      if (order.items && Array.isArray(order.items)) {
        order.items.forEach(item => {
          const productInfo = productCategoryCache.get(item.product_id)
          if (productInfo) {
            let category = productInfo.category
            // 根据类别名称映射到我们需要的类别
            if (category.includes('水果')) {
              category = '新鲜水果'
            } else if (category.includes('蔬菜')) {
              category = '绿色蔬菜'
            } else if (category.includes('肉类')) {
              category = '优质肉类'
            } else if (category.includes('海鲜')) {
              category = '新鲜海鲜'
            }
            if (category in categoryQuantities) {
              categoryQuantities[category] += Number(item.quantity) || 0
            }
          }
        })
      }
    })

    // 更新数量趋势图
    updateQuantityChart(categoryQuantities)

    console.log('采购趋势数据更新成功:', {
      amountData: {
        dateCount: amountDates.length,
        totalAmount: amounts.reduce((sum, amount) => sum + amount, 0)
      },
      quantityData: categoryQuantities
    })

  } catch (error) {
    console.error('获取采购趋势数据失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    ElMessage.error('获取采购趋势数据失败: ' + (error.message || '未知错误'))
  }
}

// 更新金额趋势图表
const updateAmountChart = (data) => {
  if (!amountChart.value) {
    console.warn('金额趋势图表未初始化')
    return
  }

  const { dates, amounts } = data
  const total = amounts.reduce((sum, amount) => sum + amount, 0)
  
  const option = {
    title: {
      text: '采购金额趋势',
      subtext: `总金额: ¥${total.toLocaleString()}`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const amount = params[0].value
        return `${params[0].axisValue}<br/>金额: ¥${amount.toLocaleString()}`
      }
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false,
      axisLabel: {
        rotate: 45,
        formatter: (value) => {
          // 根据时间范围显示不同格式
          if (amountTimeRange.value === 'week') {
            return value.substring(5) // MM-DD
          } else if (amountTimeRange.value === 'month') {
            return value.substring(5) // MM-DD
          } else {
            return value.substring(0, 7) // YYYY-MM
          }
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '金额 (元)',
      axisLabel: {
        formatter: (value) => `¥${value.toLocaleString()}`
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    series: [{
      name: '采购金额',
      type: 'line',
      data: amounts,
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(64,158,255,0.2)'
          }, {
            offset: 1,
            color: 'rgba(64,158,255,0)'
          }]
        }
      },
      emphasis: {
        itemStyle: {
          color: '#409EFF',
          borderWidth: 3
        }
      }
    }]
  }

  try {
    amountChart.value.setOption(option, true)
    console.log('金额趋势图表更新成功')
  } catch (error) {
    console.error('金额趋势图表更新失败:', error)
  }
}

// 更新数量趋势图表
const updateQuantityChart = (categoryQuantities) => {
  if (!quantityChart.value) {
    console.warn('数量趋势图表未初始化')
    return
  }

  // 转换数据为饼图格式
  const data = Object.entries(categoryQuantities).map(([name, value]) => ({
    name,
    value
  }))

  const total = Object.values(categoryQuantities).reduce((sum, value) => sum + value, 0)

  const option = {
    title: {
      text: '采购数量统计',
      subtext: `总数量: ${total}`,
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [{
      name: '采购数量',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}\n{c}个'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '16',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data: data
    }]
  }

  try {
    quantityChart.value.setOption(option, true)
    console.log('数量趋势图表更新成功')
  } catch (error) {
    console.error('数量趋势图表更新失败:', error)
  }
}

// 初始化数据
  onMounted(async () => {
  try {
    console.log('Component mounted, initializing data...')
    
    // 先初始化图表
    await nextTick()
    initCharts()

    // 等待图表初始化完成后再获取数据
    await nextTick()
    await Promise.all([
      fetchWarehouses(),
      fetchOrderStatistics(),
      fetchPurchaseTrends(),
      fetchWarehouseInventory()
    ])

    // 设置定时刷新
    const refreshInterval = setInterval(() => {
      fetchPurchaseTrends()
    }, 300000) // 每5分钟刷新一次

    // 组件卸载时清理定时器
    onUnmounted(() => {
      clearInterval(refreshInterval)
    })

    console.log('Data initialization completed')
  } catch (error) {
    console.error('Failed to initialize data:', error)
    ElMessage.error('初始化数据失败')
  }
})

// 监听时间范围变化
watch([amountTimeRange, quantityTimeRange], () => {
  fetchPurchaseTrends()
})

// 添加窗口大小变化监听
const handleResize = () => {
  nextTick(() => {
    if (amountChart.value) {
      amountChart.value.resize()
    }
    if (quantityChart.value) {
      quantityChart.value.resize()
    }
  })
}

window.addEventListener('resize', handleResize)

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (amountChart.value) {
    amountChart.value.dispose()
  }
  if (quantityChart.value) {
    quantityChart.value.dispose()
  }
})

// 计算日期范围
const calculateDateRange = (timeRange) => {
  const now = new Date()
  let startDate, endDate

  switch (timeRange) {
    case 'week':
      // 获取本周的开始（周一）和结束（周日）
      startDate = new Date(now)
      startDate.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1))
      endDate = new Date(startDate)
      endDate.setDate(startDate.getDate() + 6)
      break
    case 'month':
      // 获取本月的开始和结束
      startDate = new Date(now.getFullYear(), now.getMonth(), 1)
      endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
      break
    case 'year':
      // 获取本年的开始和结束
      startDate = new Date(now.getFullYear(), 0, 1)
      endDate = new Date(now.getFullYear(), 11, 31)
      break
    default:
      startDate = new Date(now)
      endDate = new Date(now)
  }

  // 格式化日期为 YYYY-MM-DD
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  return {
    startDate: formatDate(startDate),
    endDate: formatDate(endDate)
  }
}

// 获取用户store
const userStore = useUserStore()

// 获取订单统计数据
const fetchOrderStatistics = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 获取当前月份和上个月份的日期范围
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth() + 1
    const lastMonth = currentMonth === 1 ? 12 : currentMonth - 1
    const lastMonthYear = currentMonth === 1 ? currentYear - 1 : currentYear

    // 格式化日期
    const formatDate = (year, month) => {
      const date = new Date(Date.UTC(year, month - 1, 1))
      const lastDay = new Date(Date.UTC(year, month, 0))
      return {
        start: date.toISOString().split('T')[0],
        end: lastDay.toISOString().split('T')[0]
      }
    }

    const currentMonthDates = formatDate(currentYear, currentMonth)
    const lastMonthDates = formatDate(lastMonthYear, lastMonth)

    // 获取本月订单
    const currentMonthResponse = await axios.get('/api/purchase-orders/', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      },
      params: {
        start_date: currentMonthDates.start,
        end_date: currentMonthDates.end
      }
    })

    // 获取上月订单
    const lastMonthResponse = await axios.get('/api/purchase-orders/', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      },
      params: {
        start_date: lastMonthDates.start,
        end_date: lastMonthDates.end
      }
    })

    // 处理响应数据
    const currentMonthOrders = currentMonthResponse.data?.results || 
                             currentMonthResponse.data?.data?.items || 
                             (Array.isArray(currentMonthResponse.data) ? currentMonthResponse.data : [])

    const lastMonthOrders = lastMonthResponse.data?.results || 
                           lastMonthResponse.data?.data?.items || 
                           (Array.isArray(lastMonthResponse.data) ? lastMonthResponse.data : [])

    // 过滤有效订单（已确认、已收货、已完成）
    const validStatuses = ['confirmed', 'received', 'completed']
    const validCurrentMonthOrders = currentMonthOrders.filter(order => validStatuses.includes(order.status))
    const validLastMonthOrders = lastMonthOrders.filter(order => validStatuses.includes(order.status))

    // 计算统计数据
    const monthlyOrders = validCurrentMonthOrders.length
    const lastMonthOrderCount = validLastMonthOrders.length

    const monthlyAmount = validCurrentMonthOrders.reduce((sum, order) => sum + (Number(order.total_amount) || 0), 0)
    const lastMonthAmount = validLastMonthOrders.reduce((sum, order) => sum + (Number(order.total_amount) || 0), 0)

    // 计算增长率
    const orderGrowth = lastMonthOrderCount > 0 
      ? Math.round(((monthlyOrders - lastMonthOrderCount) / lastMonthOrderCount) * 100)
      : 100

    const amountGrowth = lastMonthAmount > 0
      ? Math.round(((monthlyAmount - lastMonthAmount) / lastMonthAmount) * 100)
      : 100

    // 更新统计数据
    statistics.value = {
      monthlyOrders,
      orderGrowth,
      monthlyAmount,
      amountGrowth,
      stockWarnings: stockWarnings.value.length,
    }

    console.log('统计数据更新成功:', statistics.value)
  } catch (error) {
    console.error('获取订单统计数据失败:', error)
    ElMessage.error('获取订单统计数据失败')
  }
}

// 监听登录状态变化
watch(() => userStore.token, async (newToken, oldToken) => {
  console.log('Token changed:', !!oldToken, '->', !!newToken)
  if (newToken) {
    await initializeData()
  }
}, { immediate: true })
  </script>
  
  <style scoped>
  .purchaser-dashboard {
    padding: 20px;
  }
  
.dashboard-header {
  margin-bottom: 20px;
}

.dashboard-header h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.dashboard-header p {
  margin: 0;
  color: #606266;
}

.dashboard-card {
    margin-bottom: 20px;
  }

.card-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.statistic-section {
  padding: 20px 0;
  border-bottom: 1px solid #EBEEF5;
}

.chart-section {
  padding-top: 10px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  }
  
  .card-header-with-icon {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .statistic-value {
  font-size: 28px;
    font-weight: bold;
    margin: 10px 0;
  color: #303133;
  }
  
  .statistic-label {
  color: #666;
    font-size: 14px;
  }
  
.warning-summary {
    margin-bottom: 20px;
  padding: 15px;
  background-color: #fef0f0;
  border-radius: 4px;
  }
  
.warning-count {
    display: flex;
    align-items: center;
  gap: 8px;
  color: #f56c6c;
  font-size: 16px;
}

.text-danger {
  color: #f56c6c;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

.warehouse-inventory-card {
  margin: 20px 0;
  }
  </style>
